using Godot;
using System;

public partial class BasicEnemy : CharacterBody2D
{

	int MAX_SPEED = 40;


	Node2D visuals;
	VelocityComponent velocityComponent;
	AudioStreamPlayer2D audioStreamPlayer2D;

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		// Area2D area2d = GetNode("HurtboxComponent") as Area2D;
		// // GD.Print(area2d);
		// area2d.AreaEntered += (otherArea)=>{
		// 	this.OnAreaEntered(otherArea);
		// };

		visuals = GetNode<Node2D>("Visuals");
		velocityComponent = GetNode<VelocityComponent>("VelocityComponent");

		GetNode<HurtboxComponent>("HurtboxComponent").Hit += OnHit;
		
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		//移动组件
		velocityComponent.AccelerateToPlayer();
		velocityComponent.Move(this);


		// Vector2 direction = this.GetDirectionToPlayer();
		// Velocity = direction * MAX_SPEED;
		// MoveAndSlide();

		var moveSign = Math.Sign(Velocity.X);
		if(moveSign != 0){
			visuals.Scale = new Vector2(-moveSign,1);
		}
	}


	public Vector2 GetDirectionToPlayer(){
		Node2D playerNode = GetTree().GetFirstNodeInGroup("player") as Node2D;
		if(playerNode != null){
			return (playerNode.GlobalPosition - GlobalPosition).Normalized();
		}
		return Vector2.Zero;
	}

	public void OnHit(){
		GetNode<RandomStreamPlayer2dComponent>("HitRandomAudioPlayerComponent").PlayRandom();
	}


}
